<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Logger\LoggerFactory;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;

abstract class AbstractController
{
    #[Inject]
    protected ContainerInterface $container;

    #[Inject]
    protected RequestInterface $request;

    #[Inject]
    protected ResponseInterface $response;

    /**
     * @var LoggerInterface
     */
    protected LoggerInterface $logger;


    /**
     * @param LoggerFactory $loggerFactory
     */
    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }


    /**
     * @param $body
     * @param int $code
     * @return \Psr\Http\Message\MessageInterface|\Psr\Http\Message\ResponseInterface
     */
    public function success($body,int $code = 200)
    {

        $data = [
            'code' => $code,
            'msg'  =>'success',
            'data' => $body,
        ];

        return $this->response->withStatus($code)->withAddedHeader('content-type', 'application/json; charset=utf-8')->withBody(new \Hyperf\HttpMessage\Stream\SwooleStream(json_encode($data)));
    }

    /**
     * @param $msg
     * @param $code
     * @return \Psr\Http\Message\MessageInterface|\Psr\Http\Message\ResponseInterface
     */
    public function error($msg,$code = 500)
    {
        $data = [
            'code' => $code,
            'msg' => $msg,
        ];

        return $this->response->withStatus($code)->withAddedHeader('content-type', 'application/json; charset=utf-8')->withBody(new \Hyperf\HttpMessage\Stream\SwooleStream(json_encode($data)));
    }
}
